/*
PearReview - The peer review assistant.
Copyright (C) 2009  Dimitrij Pankratz, Anton Musichin
http://www.pearreview.com, info@pearreview.com

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

package com.pearreview.ui.tree;

import java.awt.HeadlessException;
import java.awt.Point;
import java.awt.datatransfer.FlavorMap;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;

import javax.swing.JTree;
import javax.swing.TransferHandler;
import javax.swing.tree.TreePath;

public class ExpandPathDropTarget extends DropTarget {

	private static final long serialVersionUID = 5294973836209069376L;
	
	public static final long EXPAND_TIME = 750;
	
	private TreePath overPath = null;
	private long overStartTime = 0;

	public ExpandPathDropTarget(JTree c, DropTargetListener dtl)
			throws HeadlessException {
		super(c, dtl);
	}

	public ExpandPathDropTarget(JTree c, int ops,
			DropTargetListener dtl) throws HeadlessException {
		super(c, ops, dtl);
	}

	public ExpandPathDropTarget(JTree c, int ops,
			DropTargetListener dtl, boolean act) throws HeadlessException {
		super(c, ops, dtl, act);
	}

	public ExpandPathDropTarget(JTree c, int ops,
			DropTargetListener dtl, boolean act, FlavorMap fm)
			throws HeadlessException {
		super(c, ops, dtl, act, fm);
	}
	
	@Override
	public void dragOver(DropTargetDragEvent dtde) {	
		super.dragOver(dtde);
		
		if(!(getComponent() instanceof JTree))
			return;
		
		JTree tree = ((JTree)getComponent());
		
		Point p = dtde.getLocation();
		TreePath targetPath = 
				tree.getClosestPathForLocation(p.x, p.y);
		
		if(targetPath != null && !tree.isExpanded(targetPath)){
			if(targetPath.equals(overPath)) {
				long currentTime = System.nanoTime() / 1000000L;
				long elapsedTime = currentTime - overStartTime;
				if(elapsedTime > EXPAND_TIME) {
					
					tree.expandPath(overPath);
				}
			} else {
				overPath = targetPath;
				overStartTime = System.nanoTime() / 1000000L;
			}
		}
	}
	
	@Override
	public void dragEnter(DropTargetDragEvent dtde) {
		dtde.acceptDrag(TransferHandler.NONE);
		overPath = null;
	}
	
	@Override
	public void dragExit(DropTargetEvent dte) {
		overPath = null;
	}

}
